package com.realgodo.site.service.site;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.site.News;

@Service("newsManager")
@Transactional
public class NewsManager extends DefaultEntityManager<News, Long> {

	@Autowired
	protected SessionFactory sessionFactory;

	public News createNews(News aNews) {
		if (aNews.getId() != null) {
			News old = this.get(aNews.getId());
			aNews.setPublishDate(old.getPublishDate());
		}
		aNews.setStatus(News.PUBLISHED);
		return (News) this.saveMerge(aNews);
	}

	/**
	 * 获取首页显示
	 * @param size
	 * @return
	 */
	public List<News> findFrontNews(int size) {
		Page<News> page = new Page<News>(size);
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				News.class);
		c.add(Restrictions.eq("status", News.PUBLISHED));
		c.add(Restrictions.eq("front", News.FRONT));
		c.addOrder(Order.desc("id"));
		return this.entityDao.findByCriteria(page, c).getResult();
	}

	public Page<News> findNews(Page<News> aNewsPage, String aTitle, int status,
			boolean isFront) {
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				News.class);
		if (aTitle != null && !"".equals(aTitle)) {
			c.add(Restrictions.like("title", aTitle, MatchMode.ANYWHERE));
		}
		if (status != News.ALL) {
			c.add(Restrictions.eq("status", status));
		}
		if (isFront) {
			c.add(Restrictions.eq("front", News.FRONT));
		}
		c.addOrder(Order.desc("id"));
		aNewsPage = this.entityDao.findByCriteria(aNewsPage, c);
		return aNewsPage;
	}

	public void frontNews(Long aNewsId) {
		News _news = this.get(aNewsId);
		_news.setFront(News.FRONT);
		this.saveMerge(_news);
	}

	public void unfrontNews(Long aNewsId) {
		News _news = this.get(aNewsId);
		_news.setFront(News.NOT_FRONT);
		this.saveMerge(_news);
	}
}
